<?php

// Start Session
session_start();
require_once('Authorizer.php');
require_once('FEFunctions.php');
require_once('config.inc.php');
require_once('Validation.php');
require_once(MYSQL);
require_once(STATEM_MYSQL);

if (!isset($_POST['EventId'])) {
    session_write_close();
    header("Location: RSVP.php");
    exit();
}

//Array to store validation errors
$errmsg_arr = array();

//Validation error flag
$errflag = FALSE;

$attendance = 'P';
$guests = 0;

if (isset($_POST['NoAttending'])) {
    $attendance = 'N';
    $guests = 0;
}
else
{
    for($i = 0; $i <= MAX_NUM_ALLOW_GUESTS; $i++)
    {
        if (isset($_POST['Attending'.$i])) {
            $attendance = 'Y';
            $guests = $i;
            break;
        }
    }
}

//If Input Errors, Redirect EventCreatePage
if ($errflag) {
    $_SESSION['ERRMSG_ARR_FE'] = $errmsg_arr;
    session_write_close();
    header('Location: RSVP.php');
    exit();
}

$qAttendanceEventMember = sprintf($Q_ALL_Eventid_EventMemberAttend, $_POST['EventId'], $_SESSION['SESS_USER_EMAIL_FE_ID']);
$rAttendanceEventMember = mysqli_query($dbc, $qAttendanceEventMember) or trigger_error("Query: $qAttendanceEventMember\n<br />MySQL Error: " . mysqli_error($dbc));

$qUpdateInsertAttendance = '';
if (mysqli_num_rows ($rAttendanceEventMember) == 1)
{
    // There is already a entry, so Update
    $qUpdateInsertAttendance = sprintf($U_ALL_EventMemberAttend, $attendance, $guests, $_POST['EventId'], $_SESSION['SESS_USER_EMAIL_FE_ID']);
}
else
{
    // There is no entry, so Insert
    $qUpdateInsertAttendance = sprintf($I_ALL_EventMemberAttend, $_POST['EventId'], $_SESSION['SESS_USER_EMAIL_FE_ID'], $attendance, $guests);
}

mysqli_free_result($rAttendanceEventMember);

$rUpdateAttendance = mysqli_query($dbc, $qUpdateInsertAttendance) or trigger_error("Query: $qUpdateInsertAttendance\n<br />MySQL Error: " . mysqli_error($dbc));

//Check whether the query was successful or not
if ($rUpdateAttendance) {
    mysqli_close($dbc);
    session_write_close();
    header("Location: RSVP.php");
    exit();
} else {
    // Free DB
    mysqli_close($dbc);
    die("Query failed");
}
?>